<template>
	<view class="explain">

		<!-- 页面头部  撤销 恢复 收起白板 -->
		<view class="handleTop flex align-center justify-between" :style="{top: `${systemInfo.statusBarHeight}px`}">
			<view @click="BACKPAGE()">返回</view>
			<view class="handleTopLeft flex align-center">
				<text @click.stop="backCanvas()" class="cuIcon-repeal"
					style="color: #D8D8D8;transform: rotate(90deg);font-size: 40rpx;font-weight: bold;margin-left: 17rpx;"></text>
				<text @click.stop="nextCanvas()" class="cuIcon-repeal"
					style="color: #D8D8D8;font-size: 40rpx;font-weight: bold;margin-left: 17rpx;transform: rotate(-90deg);"></text>
			</view>
			<view class="handleTopRight" @click="putAway">
				收起白板
			</view>
		</view>
		<!-- <text class="cuIcon-back" style="font-size: 25rpx;color: #000;position: fixed;left: 20rpx;z-index: 9;" :style="{top: `calc(${systemInfo.statusBarHeight}px + 25rpx)`}"></text> -->

		<!-- 加载图片 -->
		<image class="picbg"
			:style="{height: `calc(100vh - ${systemInfo.statusBarHeight}px)`, top: `${systemInfo.statusBarHeight}px`}"
			src="../../static/logo.png" mode=""></image>

		<!-- 加载canvas 在图片上层涂鸦 -->
		<canvas
			:style="{top: `${systemInfo.statusBarHeight}px`, height: `calc(100vh - ${systemInfo.statusBarHeight}px)`}"
			ref="myCanvas" class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart"
			@touchmove="uploadScaleMove" @touchend="uploadScaleEnd" canvas-id="handWriting">
		</canvas>

		<!-- 页面底部 选择画笔 等 -->
		<view class="pageBottom flex align-center justify-around">

			<!-- 折叠 -->
			<view class="pageBottomList flex flex-direction align-center justify-between">
				<view
					style="width: 86rpx;height: 86rpx;background: rgba(0,0,0,.5);border-radius: 50%;margin-bottom: 8rpx;"
					class="flex align-center justify-around">
					<image style="width: 34rpx;height: 48rpx;" src="/static/image/zhedie.png" mode=""></image>
				</view>
				<text style="font-size: 22rpx;color: #D8D8D8;">折叠</text>
			</view>

			<!-- 画笔 -->
			<view @click="openPen" class="pageBottomList flex flex-direction align-center justify-between">
				<view
					style="width: 86rpx;height: 86rpx;background: rgba(0,0,0,.5);border-radius: 50%;margin-bottom: 8rpx;"
					class="flex align-center justify-around">
					<image style="width: 34rpx;height: 48rpx;" src="/static/image/huabi.png" mode=""></image>
				</view>
				<text :class="isCurren == 1 ? 'isCurrenWords' : null" style="font-size: 22rpx;color: #D8D8D8;">画笔</text>
			</view>

			<!-- 荧光笔 -->
			<view class="pageBottomList flex flex-direction align-center justify-between" @click="openYg">
				<view
					style="width: 86rpx;height: 86rpx;background: rgba(0,0,0,.5);border-radius: 50%;margin-bottom: 8rpx;"
					class="flex align-center justify-around">
					<image style="width: 34rpx;height: 48rpx;" src="/static/image/yingguangbi.png" mode=""></image>
				</view>
				<text :class="isCurren == 2 ? 'isCurrenWords' : null"
					style="font-size: 22rpx;color: #D8D8D8;">荧光笔</text>
			</view>

			<!-- 文字 -->
			<view class="pageBottomList flex flex-direction align-center justify-between"
				@click="$refs.wordsPopup.open()">
				<view
					style="width: 86rpx;height: 86rpx;background: rgba(0,0,0,.5);border-radius: 50%;margin-bottom: 8rpx;"
					class="flex align-center justify-around">
					<image style="width: 50rpx;height: 50rpx;" src="/static/image/wenzi.png" mode=""></image>
				</view>
				<text :class="isCurren == 3 ? 'isCurrenWords' : null" style="font-size: 22rpx;color: #D8D8D8;">文字</text>
			</view>

			<!-- 橡皮 -->
			<view class="pageBottomList flex flex-direction align-center justify-between" @click="action = 'rubber'">
				<view
					style="width: 86rpx;height: 86rpx;background: rgba(0,0,0,.5);border-radius: 50%;margin-bottom: 8rpx;"
					class="flex align-center justify-around">
					<image style="width: 50rpx;height: 50rpx;" src="/static/image/xiangpi.png" mode=""></image>
				</view>
				<text :class="action == 'rubber' ? 'isCurrenWords' : null"
					style="font-size: 22rpx;color: #D8D8D8;">橡皮</text>
			</view>

			<!-- 更多 -->
			<view class="pageBottomList flex flex-direction align-center justify-between">
				<view
					style="width: 86rpx;height: 86rpx;background: rgba(0,0,0,.5);border-radius: 50%;margin-bottom: 8rpx;"
					class="flex align-center justify-around">
					<image style="width: 46rpx;height: 10rpx;" src="/static/image/gengduo.png" mode=""></image>
				</view>
				<text :class="isCurren == 5 ? 'isCurrenWords' : null" style="font-size: 22rpx;color: #D8D8D8;">更多</text>
			</view>
		</view>

		<!-- 画布文字 -->
		<view :disable-scroll="true" class="wordsPos" v-for="(im, ix) in wordsList" :key="ix" :style="im.style"
			@touchmove.stop.preven="(event) => {wordsClick(event,ix)}">
			{{im.words}}
		</view>

		<!-- 画笔的选项 -->
		<uni-popup type="bottom" ref="selectPenType">
			<view class="selectPenType">
				<view class="selectPenTypeSize flex align-center justify-around">
					<view v-for="(item,index) in selectPenTypeSize"
						:style="{borderRightColor: lineSize == item ? '#FC2C1C' : '', borderRightWidth: item + 'rpx'}"
						@click="lineSize = item" class="selectPenTypeSizeList"></view>
				</view>
				<view class="selectPenTypeColor flex align-center justify-around">
					<view @click="lineColor = item" v-for="(item,index) in selectPenTypeColorlist" class="">
						<view style="width: 65rpx;height: 65rpx;border-radius: 8rpx;" :style="{borderColor: item,}"
							:class="lineColor == item ? 'isCheckLine' : ''" class="flex align-center justify-around">
							<view :style="{background: item}" class="selectPenTypeColorlist"></view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 画布文字弹窗 -->
		<uni-popup ref="wordsPopup" type="dialog">
			<uni-popup-dialog mode="input" title="请输入文字" :duration="2000" :before-close="true"
				@close="$refs.wordsPopup.close()" @confirm="wordsConfirm"></uni-popup-dialog>
		</uni-popup>

		<video v-if="canUrl" :src="canUrl" controls></video>

		<audio></audio>

	</view>
</template>

<script>
	import { socket } from '../../utils/scoket.js'
	export default {
		name: 'explain',
		data() {
			return {
				canUrl: null,
				systemInfo: {},
				ctx: null, // canvas操作实例
				lineColor: '#000000', // 画笔颜色
				lineSize: 2, // 画笔大小
				lineHistory: [], // 画笔历史路径
				historyPointer: -1, // 记录回退按钮
				lineNow: [], // 画笔当前路径
				action: 'pen', // pen 铅笔 ygpen 荧光笔 text 文字 rubber 橡皮擦
				isCurren: 1,
				selectPenTypeColorlist: ['#000000', '#949699', '#E62322', '#FE6A0C', '#F6B600', '#02BF51', '#44D6B6',
					'#016FFE', '#6136FE'
				],
				selectPenTypeSize: [2, 5, 8, 12, 15],
				wordsList: [],
				urlImg: '../../static/logo.png'
			}
		},
		watch: {
			lineSize() {
				console.log(this.lineSize)
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: res => this.systemInfo = res
			})
			socket.init()
		},
		onReady() {
			let ctx = uni.createCanvasContext('handWriting', this);
			this.ctx = ctx;
			
			this.ctx.drawImage(this.urlImg,0, 0, )

			setTimeout(() => {
				this.canverStream()
			}, 2000)

		},
		methods: {

			async canverStream() {
				
				// encodeURIComponent(`ws://192.168.110.1:3001/rtmp/rtmp%3A%2F%2F127.0.0.1%3A1935%2Flive%2FrfBd56ti2SMtYvSgD5xAV0YU99zampta7Z7S575KLkIZ9PYk`)
				
				// ws://:3001/rtmp/rtmp%3A%2F%2F127.0.0.1%3A1935%2Flive%2FrfBd56ti2SMtYvSgD5xAV0YU99zampta7Z7S575KLkIZ9PYk

// let url = 'ws://172.16.201.181:3001/rtmp/rtmp' + encodeURIComponent(`%3A%2F%2F127.0.0.1%3A1935%2Flive%2FrfBd56ti2SMtYvSgD5xAV0YU99zampta7Z7S575KLkIZ9PYk`)

// let url = `ws://172.16.201.33:3000/rtmp/rtmp%3A%2F%2F123.56.80.122%2Flive%2Flivestream.flv`

// console.log(url)

				// const ws = new WebSocket(url);

				// ws.addEventListener('open', (e) => {

					const mediaStream = new MediaStream();

					// 添加视频轨
					const video = document.querySelector('canvas').captureStream(30);
					video.getTracks().forEach(mediaStream.addTrack.bind(mediaStream));

					// 添加音频轨（From <audio> element）
					// const audioContext = new AudioContext();
					// const audioSrc = audioContext.createMediaElementSource(document.querySelector('audio'));
					// const destination = audioContext.createMediaStreamDestination();
					// audioSrc.connect(destination);
					// destination.stream.getTracks().forEach(mediaStream.addTrack.bind(mediaStream));

					// 创建 MediaRecorder
					const mediaRecorder = new MediaRecorder(mediaStream, {
						mimeType: 'video/webm;codecs=h264',
						audioBitsPerSecond: 44100, // 44.1kHz
						videoBitsPerSecond: 3000000 // 3000k 画质
					});
					mediaRecorder.addEventListener('dataavailable', (e) => {
						// 将数据发送到后台
						// 发送时 e.data 的类型是 Blob
						console.log(e.data, 'e.datae.datae.data')
						socket.send('send', ret => console.log(ret,'retretretret'))
					});
					mediaRecorder.start(1000);

				// });
				
				
				// ws.onclose = function (e) {
				// 	console.log('=========================')
				//   console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
				//   console.log(e)
				// }
				
				
			},

			putAway() {
				console.log(111111)
			},
			openPen() {
				this.action = 'pen'
				this.$refs.selectPenType.open()
			},
			openYg() {
				this.action = 'ygpen'
				this.$refs.selectPenType.open()
			},
			wordsConfirm(value) {
				console.log(value)

				this.wordsList.push({
					words: value,
					style: {
						top: '200rpx',
						left: '20rpx'
					}
				})

				this.$refs.wordsPopup.close()
			},
			wordsClick(event, ix) {

				this.wordsList[ix].style.top = (event.touches[0].pageY) + 'px'
				this.wordsList[ix].style.left = (event.touches[0].pageX) + 'px'

				this.$forceUpdate()
			},








			/* 画布 start */

			// 回退
			backCanvas() {
				console.log(111)
				if (this.historyPointer == -1) {
					return
				}
				this.historyPointer -= 1
				this.reDraw()
			},
			// 恢复回退内容
			nextCanvas() {
				if (this.historyPointer == this.lineHistory.length - 1) {
					return
				}
				this.historyPointer += 1
				this.reDraw()
			},
			// 清除画布重新绘制
			reDraw() {
				const {
					ctx
				} = this

				// 清除画布
				ctx.clearRect(0, 0, 99999, 99999)
				ctx.draw(true)

				// 循环历史笔迹
				for (let i = 0; i <= this.historyPointer; i++) {
					this.pointLine(this.lineHistory[i])
				}

			},
			// 画笔开始
			uploadScaleStart(e) {

				this.lineNow = []

				const {
					ctx
				} = this
				// 第一位是起始点
				this.lineNow.push({
					lineX: e.touches[0].x,
					lineY: e.touches[0].y,
					color: this.lineColor,
					lineSize: this.lineSize,
					action: this.action
				})
				console.log(this.lineNow)
				this.pointLine(this.lineNow)

				// ctx.beginPath()
				// ctx.moveTo(this.lineNow[0].lineX, this.lineNow[0].lineY);

			},
			// 画笔移动
			uploadScaleMove(e) {
				const {
					ctx
				} = this

				this.lineNow.push({
					lineX: e.touches[0].x,
					lineY: e.touches[0].y
				})
				this.pointLine(this.lineNow)

			},
			// 画笔结束
			uploadScaleEnd(e) {

				if (this.historyPointer < this.lineHistory.length - 1) {
					let tempFlag = this.lineHistory.length - this.historyPointer
					for (let i = tempFlag - 1; i; i--) {
						this.lineHistory.pop()
					}
				}
				this.historyPointer++
				this.lineHistory.push(this.lineNow)

			},
			// 画线条
			pointLine(lineNow, x, y, type) {
				const {
					ctx
				} = this

				// 笔迹起点
				ctx.beginPath()
				// moveto 将坐标移到xy轴
				ctx.moveTo(lineNow[0].lineX, lineNow[0].lineY);
				ctx.setLineWidth(lineNow[0].lineSize)
				ctx.setFillStyle(lineNow[0].color);

				let isRubber = false
				if (lineNow[0].action == 'rubber') {
					isRubber = true
				}

				if (lineNow[0].action == 'ygpen') {
					ctx.setStrokeStyle('rgba(255, 255, 255, 1)')
					ctx.setShadow(5, 5, 20, lineNow[0].color)
					ctx.setGlobalAlpha(0.1)
				} else {
					ctx.setStrokeStyle(lineNow[0].color)
					ctx.setShadow(0, 0, 0, lineNow[0].color)
					ctx.setGlobalAlpha(1)
				}

				// 循环坐标
				lineNow.forEach((im, ix) => {
					if (isRubber) {
						ctx.clearRect(im.lineX, im.lineY, 20, 20)
						return
					}
					this.ctx.lineTo(im.lineX, im.lineY)
					this.ctx.stroke()
				})
				this.ctx.draw(true)

				this.$forceUpdate()
			}

			/* 画布 End */
		}
	}
</script>

<style lang="scss" scoped>
	.explain {
		.isCheckLine {
			border: 1rpx solid #0000FF;
		}

		.selectPenTypeColorlist {
			width: 50rpx;
			height: 50rpx;
			border-radius: 6rpx;
			background: #0ff;
		}

		.selectPenTypeColor {
			width: 100%;
			height: 112rpx;
		}

		.selectPenTypeSizeList {
			width: 40rpx;
			height: 60rpx;
			font-size: 40rpx;
			border-right: 1rpx solid #333333;
			transform: rotate(-45deg);
		}

		.selectPenTypeSize {
			width: 100%;
			height: 114rpx;
			border-bottom: 1rpx solid #D8D8D8;
		}

		.selectPenType {
			margin-left: 19rpx;
			margin-right: 19rpx;
			height: 230rpx;
			background: #FFFFFF;
			border-radius: 14rpx;
			margin-bottom: 30rpx;
		}

		.isCurrenWords {
			color: #FC2C1C !important;
		}

		.pageBottom {
			height: 150rpx;
			width: 100vw;
			position: fixed;
			bottom: 0;
			left: 0;
			z-index: 10;
		}

		.handleTop {
			width: 100vw;
			height: 90rpx;
			background: rgba($color: #000000, $alpha: .5);
			position: fixed;
			left: 0;
			z-index: 90;
		}

		.picbg {
			width: 100vw;
			position: fixed;
			left: 0;
			z-index: 3;
		}

		.handWriting {
			width: 100vw;
			border: 1rpx solid #007AFF;
			// background: rgba($color);
			position: fixed;
			left: 0;
			z-index: 5;
		}

		.handleTopRight {
			font-size: 26rpx;
			color: #FC2C1C;
			margin-right: 21rpx;
		}

		.handleTopLeft {
			position: relative;
			z-index: 999;
		}

		.wordsPos {
			color: #007AFF;
			position: fixed;
			z-index: 9;
		}
	}
</style>
